// pages/musicPlay/musicPlay.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    sms: '',
    show: false,
    songs: [],
    downloadIndex:0,
    // 当前播放歌曲的信息
    music: {
      id: Number,
      poster: '',
      name: '',
      author: '',
      src: ''
    },
    musicList:app.globalData.musicList,
    musicListIndex:app.globalData.musicListIndex,
    playControls:'stop',
    audioAction: {
      method: 'pause'
    }
  },
  // Promise封装获取音乐信息请求
  getMusic (keywords) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:3000/search',
        data: {
          keywords: keywords
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data && res.data.code === 200) {
            resolve(res.data)
          }
        },
        fail(error) {
          reject(error)
        }
      })
    })
  },
  // Promise封装获取音乐src请求
  getMusicSrc (id) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:3000/song/url',
        data: {
          id: id
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data && res.data.code === 200) {
            resolve(res.data)
          }
        },
        fail(error) {
          reject(error)
        }
      })
    })
  },
   // 搜索歌曲发起获取音乐信息请求
  async setMusic (keywords) {
    let data = await this.getMusic(keywords).then((value) => {
      console.log("搜索请求返回的内容", value.result);
      return value;
    })
    this.setData({
      ['songs']: data.result.songs
    })
  },
    // 发起获取音乐src请求
  async setMusicSrc (id) {
    let data = await this.getMusicSrc(id).then((res) => {
      console.log("请求返回的内容", res);
      return res;
    })
    this.setData({
      ['music.src']: data.data[0].url
    })
  },
  // 发起下载音乐请求
  async downloadMusic(){
    console.log('downloadMusic');
    let index = this.data.downloadIndex
    let id = this.data.songs[index].id;
    let fileUrl = await this.getMusicSrc(id).then((value) => {
        return value.data[0].url
    })
    console.log(fileUrl);

    wx.downloadFile({
      url: fileUrl,
      success (res) {
        console.log(res);
        if (res.statusCode === 200) {
          console.log(res.tempFilePath);
        }
      },
      fail(error){
        console.log('fail');
      }
  })
  },

  // 搜索音乐（多此一举）
  seachMusic () {
    console.log(this.data.sms);
    this.setMusic(this.data.sms)
  },
  // 获取要播放音乐的数据
  onPlayClick (event){
    // 获取当前列的index
    console.log(event.currentTarget.dataset.index);
    let index = event.currentTarget.dataset.index;
    if(this.data.music.id !== this.data.songs[index].id){
      this.setData({
        ['playControls']: 'stop'
      });
    }
    this.setData({
      ['music.id']: this.data.songs[index].id,
      ['music.name']: this.data.songs[index].name,
      ['music.poster']: this.data.songs[index].artists[0].img1v1Url,
      ['music.author']: this.data.songs[index].artists[0].name
    });
    this.setMusicSrc(this.data.music.id);
    // 由于函数有异步操作所以使用setTimeout延时触发将playControls()函数改造成异步的并在最后触发
    setTimeout(()=>{
      this.playControls()
    },500)
  },
  // 播放音乐
  playAudio (){
    this.setData({
      audioAction: {
        method: 'play',
      }
    })
  },   
  // 暂停音乐 
  pauseAudio () {
    this.setData({
      audioAction: {
        method: 'pause',
      }
    });
  },
  // 改变图标为pause
  changIconPause(){
    this.setData({
      ['playControls']:'pause'
    })
  },
  // 改变图标为Stop
  changeIconStop(){
    this.setData({
      ['playControls']:'stop'
    })
  },
  // 音乐播放控制
  playControls () {
    if(this.data.playControls == 'stop'){
      console.log("play");
      this.playAudio();
      this.changIconPause();
    }
    else if(this.data.playControls == 'pause' ){
      console.log("pause");
      this.pauseAudio();
      this.changeIconStop();
    }
  },
  // 展示弹出层
  showPopup() {
    this.setData({ show: true });
  },
  // 关闭弹出层
  onClose() {
    this.setData({ show: false });
  },
  // 保存当前行的index
  saveIndex(event){
    this.setData({
      downloadIndex: event.currentTarget.dataset.index
    })
  },
  // 添加到播放列表
  addMusicList(){
    console.log('addMusicList');
    let index = this.data.downloadIndex;
    let id = this.data.songs[index].id;
    // this.data.musicList.push(id);
    app.globalData.musicList.push(id)
    console.log(this.data.musicList);
  },
  // 播放歌单下一首歌
  nextAudio(){
    console.log('nextAudio');
    if(this.data.musicListIndex < this.data.musicList.length-1){
      this.data.musicListIndex++;
      this.changeIconStop();
      this.nowAudio();
    }
    else{
      this.data.musicListIndex = this.data.musicList.length-1;
      this.playControls()
    }
  },
  // 播放当前歌曲
  async nowAudio(){
    let data = await this.getMusic(this.data.musicList[this.data.musicListIndex]).then((value) => {
      console.log("nextAudio返回的内容", value.result);
      return value;
    })
    this.setMusicSrc(this.data.musicList[this.data.musicListIndex])
    this.setData({
      ['music.id']: data.result.songs[0].id,
      ['music.name']: data.result.songs[0].name,
      ['music.poster']: data.result.songs[0].artists[0].img1v1Url,
      ['music.author']: data.result.songs[0].artists[0].name
    });
    console.log("data:",data);
    if(this.data.musicListIndex !== 0){
      console.log(this.data.musicListIndex);
      // 由于函数有异步操作所以使用setTimeout延时触发将playControls()函数改造成异步的并在最后触发
      setTimeout(()=>{
        this.playControls()
      },500)
    }
  },
  // 播放歌单前一首歌曲
   prevAudio(){
    console.log('prevAudio');
    if(this.data.musicListIndex == 0){
      this.data.musicListIndex = 0;
      this.playControls()
    }
    else{
      this.data.musicListIndex--;
      this.changeIconStop();
      this.nowAudio()
    }
  },
  // 同步musicList
  upDateMusicList(){
    this.setData({
      musicList:app.globalData.musicList,
      musicListIndex: app.globalData.musicListIndex
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setMusic('有何不可')
    this.nowAudio()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */ 
  onReady: function () {
    // 创建音频组件
    this.audioCtx = wx.createAudioContext('myAudio')
    app.globalData.audioCtx = this.audioCtx;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 同步MusicList
    this.upDateMusicList()
    console.log(this.data.musicList);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})